package hotel.gateway;

import hotel.rmi.HotelService;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.Naming;
import java.rmi.NotBoundException;

public class HotelGw {

	static final public short PORT = 4444;

	HotelService service;

	ServerSocket serverSocket;

	Socket clientSocket;

	void handleRequest() throws IOException {
		clientSocket = serverSocket.accept();
		try {
			InputStream is = clientSocket.getInputStream();
			OutputStream os = clientSocket.getOutputStream();
			BufferedOutputStream bos = new BufferedOutputStream(os);
			DataInputStream dis = new DataInputStream(is);
			DataOutputStream dos = new DataOutputStream(bos);
			new Dispatcher(service, dos, dis).doHandleRequest();
			dos.close();
			dis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		clientSocket.close();
	}

	void start(String hostname) throws NotBoundException, IOException {
		String adress = "rmi://" + hostname + "/CalculatorService";
		service = (HotelService) Naming.lookup(adress);
		serverSocket = new ServerSocket(PORT);
		while (true) {
			try {
				handleRequest();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// serverSocket.close();
	}

	public static void main(String args[]) throws NotBoundException,
			IOException {
		if (args.length == 1)
			new HotelGw().start(args[0]);
		else
			System.out.println("Usage: hotelgw <host>");
	}
}
